const {
  to
} = require('./utils/to')
const {
  getUserType,
} = require('./utils/strorage')
const {
  USER_TYPE
} = require('./constant/index');

App({
  to,
  showToast(option) {
    let opt = {
      duration: 2000,
      mask: false,
      icon: 'none'
    }
    if (typeof option === 'string') {
      opt.title = option
    } else if (option !== undefined) {
      opt = {
        ...opt,
        success: option.onClose,
        icon: option.type,
        title: option.message
      }
    }
    setTimeout(() => {
      wx.showToast(opt)
    }, 50)
  },

  openLoading(text) {
    wx.showLoading({
      title: text || '加载中',
      mask: true
    })
  },

  closeLoading() {
    setTimeout(() => {
      wx.hideLoading()
    }, 0)
  },

  getEventData(event) {
    return event.currentTarget.dataset || {};
  },

  rootUrl(path) {
    const userType = getUserType()
    let subpackagesRoot = 'page-repair'
    if ([USER_TYPE.CUSTOMER_USER, USER_TYPE.CUSTOMER_MANAGER].includes(userType)) {
      subpackagesRoot = 'page-client'
    }
    return `/${subpackagesRoot}/${path}`
  },

  routeWithToken(url, closeCurrentPage = false) {
    // const status = this.checkLoginState()
    let routeObjectName = 'navigateTo'

    if (closeCurrentPage) {
      routeObjectName = 'reLaunch'
    }
    // if (!status) return
    wx[routeObjectName]({
      url,
      fail: () => {
        wx.reLaunch({
          url
        })
      }
    })
  },

  backParentLoad(delta = 0) {
    const pages = getCurrentPages();
    const parentPages = pages[pages.length - 2 - delta]

    if (parentPages && parentPages.onLoad) {
      parentPages.onLoad()
    }

    wx.navigateBack({
      delta: delta + 1,
      fail: () => {
        wx.reLaunch({
          url: '/tabbar/index/index',
        })
      }
    })
  },

  globalData: {
    userInfo: null,
    subpackagesRoot: 'page-repair',
  }
})